package com.hmdp.utils;

import cn.hutool.core.util.BooleanUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import java.util.function.Function;


@Component
public class CaCheClient {

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    /*获取锁*/
    private boolean tryBlock(String key) {
        Boolean flag = stringRedisTemplate.opsForValue().setIfAbsent(key, "1", 10, TimeUnit.SECONDS);
        return BooleanUtil.isTrue(flag);
    }

    /*释放锁*/
    private void delBlock(String key) {
        stringRedisTemplate.delete(key);
    }


    public void set(String key, Object value, Long time, TimeUnit unit) {
        stringRedisTemplate.opsForValue().set(key, JSONUtil.toJsonStr(value), time, unit);
    }

    /*设置逻辑过期时间*/
    public void setWithLogicExpire(String key, Object value, Long time, TimeUnit unit) {
        RedisData redisData = new RedisData();
        redisData.setData(value);
        redisData.setExpireTime(LocalDateTime.now().plusSeconds(unit.toSeconds(time)));
        //写入redis
        stringRedisTemplate.opsForValue().set(key, JSONUtil.toJsonStr(redisData));
    }

    /*缓存穿透*/
    public <R, ID> R queryWithPassThrough(String keyPrefix, ID id, Class<R> type, Function<ID, R> dbFallback, Long time, TimeUnit unit) {//Function<T,R>T是参数，R是返回值
        /*先从redis里面查缓存*/
        String key = keyPrefix + id;//定义一个key
        String Json = stringRedisTemplate.opsForValue().get(key);//得到json格式的数据
        if (StrUtil.isNotBlank(Json)) {
            /*如果有，直接返回*/
            return JSONUtil.toBean(Json, type);//反序列化成javabean对象
        }

        if (Json != null) {
            //命中到空值了
            return null;
        }
        /*如果redis里面没有数据，走数据库查*/
        R r = dbFallback.apply(id);
        if (r == null) {
            /*从数据库查看是否有相应的数据*/
            /*没有，给redis中缓存空字符串并返回错误信息*/
            stringRedisTemplate.opsForValue().set(key, "", RedisConstants.CACHE_NULL_TTL, TimeUnit.MINUTES);
            return null;
        }
        /*有，先写进redis*/
        this.set(key, r, time, unit);
        /*返回数据*/
        return r;
    }

    //声明一个线程池
    private static final ExecutorService CACHE_REBUILD_EXECUTOR = Executors.newFixedThreadPool(10);

    /*基于逻辑过期解决缓存击穿*/
    private <R, ID> R queryWithLogicExpire(ID id, String keyPrefix, Class<R> type, Function<ID, R> dbFallback, Long time, TimeUnit unit) {
        String key = keyPrefix + id;
        String Json = stringRedisTemplate.opsForValue().get(key);
        //未命中redis，直接返回空
        if (StrUtil.isBlank(Json)) {
            return null;
        }
        RedisData redisData = JSONUtil.toBean(Json, RedisData.class);
        R r = JSONUtil.toBean((JSONObject) redisData.getData(), type);
        //命中
        //判断缓存是否过期
        //未过期，返回商铺信息
        if (redisData.getExpireTime().isAfter(LocalDateTime.now())) {
            return r;
        }
        if (tryBlock(key)) {
            //过期，尝试获取互斥锁
            //获取到了，开始独立线程
            CACHE_REBUILD_EXECUTOR.submit(() -> {
                try {
                    //查询数据库
                    R r1 = dbFallback.apply(id);
                    //写入缓存
                    this.setWithLogicExpire(key, r1, time, unit);
                } catch (Exception e) {
                    throw new RuntimeException(e);
                } finally {
                    //释放锁
                    delBlock(key);
                }
            });
        }
        //没有获取到，返回过期的店铺信息
        return r;
    }
}
